#include <iostream>
#include <pqxx/pqxx> 
#include <fstream>
#include <sstream>

#define SIZE 46
#define YEAR 2011

using namespace std;
using namespace pqxx;


void get_px_NDVI_serie( int, int, int, double[], double );
void clear_array(double[], int);
void print_array(double[], int);

int main()
{
	double a[46];
	clear_array(a, SIZE);
	get_px_NDVI_serie(YEAR, 2300, 2300, a, 2000);
	print_array(a, SIZE);
	return 0;
}

void get_px_NDVI_serie(int year, int line, int sample, double ndvi_serie[], double xiao_threshold_sur_refl_b03 )
{
	string sql;
	stringstream sqlstream;
	   
	try{
		connection C("dbname=mymodisdb user=demo1usr password=demo1pwd hostaddr=127.0.0.1 port=5432");
		if ( !C.is_open() ) { return; }

		sqlstream.str("");
		sqlstream << "\
			SELECT pixels.px_x, pixels.px_y, pixels.date_tkn, pixels.ndvi, pixels.lswi, pixels.evi, pixels.sur_refl_b03 \
			FROM public.pixels \
			WHERE px_x = "<< line <<" and px_y = "<< sample <<" \
			ORDER BY pixels.date_tkn \
			LIMIT 46 OFFSET "<< 46*(year-2009);
		sql = sqlstream.str();
		nontransaction N(C);
		result R( N.exec( sql ));

		int date = 0;
		double ndvi;
		for (result::const_iterator c = R.begin(); c != R.end(); ++c)
		{
			ndvi = 0.0;
			if ( c[6].as<double>() < xiao_threshold_sur_refl_b03 ){
				ndvi = c[3].as<double>();
			}
			ndvi_serie[date] = ndvi;
			date++;
		}
		C.disconnect ();
	}catch (const std::exception &e){
		cerr << e.what() << std::endl;
		return;
	}
}

void clear_array(double a[], int size)
{
	for (int i = 0; i < size ; i++ ){
		a[i] = 0;
	}
}

void print_array(double a[], int size){
	for (int i = 0; i < size; ++i)
	{
		cout << a[i] << " ";
	}
	cout << endl;
}